<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="请输入应用名称" v-model="listQuery.appName"></el-input>
      <el-button class="filter-item" type="primary" style="float:right;"  icon="el-icon-edit"  @click="handleCreate">新增</el-button>
      <el-button class="filter-item" type="primary" style="float:right;margin-right:10px;" v-waves icon="el-icon-search" @click="handleFilter">查询</el-button>
    </div>
    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="正在加载中" border fit highlight-current-row
      style="width: 100%">
      <el-table-column align="center" label="行号" width="65">
        <template slot-scope="scope">
          <span>{{scope.$index+1}}</span>
        </template>
      </el-table-column>
      <el-table-column width="150px" align="center" label="应用名称">
        <template slot-scope="scope">
          <span>{{scope.row.appName }}</span>
        </template>
      </el-table-column>
      <el-table-column width="150px" align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.gmtCreate | formatDatetime}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="70px" label="应用版本">
        <template slot-scope="scope">
          <span class="link-type" >{{scope.row.fileVersion}}</span>
        </template>
      </el-table-column>
      <el-table-column width="80px" align="center" label="上架状态">
        <template slot-scope="scope">
          <span>{{scope.row.status }}</span>
        </template>
      </el-table-column>
      <el-table-column width="80px" align="center" label="应用标识">
        <template slot-scope="scope">
          <span>{{scope.row.appType}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="版本描述">
        <template slot-scope="scope">
          <span>{{scope.row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="420" class-name="small-padding fixed-width">
        <template slot-scope="scope">
         <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
         <el-button type="success" size="mini" @click="handleDetail(scope.row)">详情</el-button>
         <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
         <el-button type="primary" size="mini" @click="handleDownload(scope.row)">下载</el-button>
         <el-button type="primary" size="mini" @click="handlePublish(scope.row)">发布</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="90px" style='width: 450px; margin-left:50px;'>
        <el-input type="hidden" v-model="temp.id"></el-input>
        <el-input type="hidden" v-model="temp.appId"></el-input>
        <el-form-item label="应用名称" prop="appName">
          <el-input v-model="temp.appName" readonly="readonly" ></el-input>
          <el-button type="primary" size="mini" @click="selectAppinfo()">查询</el-button>
        </el-form-item>
        <el-form-item label="版本名称" prop="fileVersion">
          <el-input v-model="temp.fileVersion"></el-input>
        </el-form-item>
        <el-form-item label="选择文件" prop="fileVersion">
          <el-upload
              class="upload-demo"
              :headers="fileHeaders"
              ref="upload"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :file-list="fileList"
              :auto-upload="false">
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
              <div slot="tip" class="el-upload__tip">只能上传文件，且不超过500kb</div>
            </el-upload>
        </el-form-item>
        <el-form-item label="remark" prop="remark">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="Please input" v-model="temp.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">cancel</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">confirm</el-button>
        <el-button v-else type="primary" @click="updateData">confirm</el-button>
      </div>
    </el-dialog>


    <el-dialog title="detail" :visible.sync="dialogDetailVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="90px" style='width: 450px; margin-left:50px;'>
       <el-input type="hidden" v-model="temp.id"></el-input>
        <el-input type="hidden" v-model="temp.appId"></el-input>
        <el-form-item label="应用名称" prop="appName">
          <el-input v-model="temp.appName"></el-input>
        </el-form-item>
        <el-form-item label="版本名称" prop="fileVersion">
          <el-input v-model="temp.fileVersion"></el-input>
        </el-form-item>
        <el-form-item label="选择文件" prop="fileStoreId">
          <el-upload
              class="upload-demo"
              :headers="fileHeaders"
              ref="upload"
              name="file"
              action="https://jsonplaceholder.typicode.com/posts/"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              :auto-upload="false">
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
              <div slot="tip" class="el-upload__tip">上传apk文件，且不超过30MB</div>
            </el-upload>
        </el-form-item>
        <el-form-item label="remark" prop="remark">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="Please input" v-model="temp.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogDetailVisible = false">CLOSE</el-button>
      </span>
    </el-dialog>

    <el-dialog title="应用信息列表" :visible.sync="dialogAppinfoSelectVisible">
      <div class="filter-container">
        <el-input @keyup.enter.native="handleFilterN" style="width: 200px;" class="filter-item" placeholder="请输入硬件序列号" v-model="listQueryN.appName"></el-input>
      <el-button class="filter-item" type="primary" style="float:right;margin-right:10px;" v-waves icon="el-icon-search" @click="handleFilterN">查询</el-button>
    </div>
    <el-table :key='tableKey' :data="listN" v-loading="listLoadingN" element-loading-text="正在加载中" border fit highlight-current-row
      style="width: 100%">
        <el-table-column align="center" label="行号" width="65">
          <template slot-scope="scope">
            <span>{{scope.$index+1}}</span>
          </template>
        </el-table-column>
        <el-table-column width="150px" align="center" label="应用名称">
          <template slot-scope="scope">
            <span>{{scope.row.appName }}</span>
          </template>
        </el-table-column>
        <el-table-column width="150px" align="center" label="申请时间">
          <template slot-scope="scope">
            <span>{{scope.row.gmtCreate | formatDatetime}}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="100px" label="应用标识">
          <template slot-scope="scope">
            <span class="link-type" >{{scope.row.appType}}</span>
          </template>
        </el-table-column>
        <el-table-column width="110px" align="center" label="描述">
          <template slot-scope="scope">
            <span>{{scope.row.remark}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleSelect(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination background @size-change="handleSizeChangeN" @current-change="handleCurrentChangeN" :current-page="listQueryN.page" :page-sizes="[10,20,30, 50]" :page-size="listQueryN.limit" layout="total, sizes, prev, pager, next, jumper" :total="totalN">
        </el-pagination>
    </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogAppinfoSelectVisible = false">CLOSE</el-button>
      </span>
    </el-dialog>

     <el-dialog title="终端发布" :visible.sync="dialogAllocationVisible">
          <div class="filter-container">
      <el-input @keyup.enter.native="handleFilterN" style="width: 200px;" class="filter-item" placeholder="请输入硬件序列号" v-model="listQueryEq.equipmentId"></el-input>
      <el-button class="filter-item" type="primary" style="float:right;margin-right:10px;" v-waves icon="el-icon-search" @click="handleFilterEq">查询</el-button>
    </div>
    <el-table :key='tableKey' :data="listEq" v-loading="listLoadingEq" element-loading-text="正在加载中" border fit highlight-current-row
      style="width: 100%" @selection-change="handleSelectionChange">>
        <el-table-column align="center" label="行号" type="selection" width="65">
        </el-table-column>
        <el-table-column width="150px" align="center" label="硬件序列号">
          <template slot-scope="scope">
            <span>{{scope.row.equipmentId }}</span>
          </template>
        </el-table-column>
        <el-table-column width="110px" align="center" label="厂商">
          <template slot-scope="scope">
            <span>{{scope.row.equipmentPro}}</span>
          </template>
        </el-table-column>
        <el-table-column width="110px" align="center" label="终端型号">
          <template slot-scope="scope">
            <span>{{scope.row.equipmentType}}</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination background @size-change="handleSizeChangeEq" @current-change="handleCurrentChangeEq" :current-page="listQueryEq.page" :page-sizes="[10,20,30, 50]" :page-size="listQueryEq.limit" layout="total, sizes, prev, pager, next, jumper" :total="totalEq">
        </el-pagination>
      </div>
      <el-form :rules="rulesEq" ref="eqdataForm" :model="tempEq" label-position="left" label-width="90px" style='width: 450px; margin-left:50px;'>
        <el-form-item label="remark" prop="remark">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="Please input" v-model="tempEq.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogAllocationVisible = false">CLOSE</el-button>
        <el-button  type="primary" @click="saveVersionPublish">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getAppInfoFilePageList, saveAppInfoFile, updateAppInfoFile, getAppInfoFileDetail, deleteAppInfoFile } from '@/api/itims/appinfofile'
import { getAppInfoPageList } from '@/api/itims/appinfo'
import { getTerminalList, getTerminalListByGroupId} from '@/api/itims/itimsterminal'
import { saveVersionPublish } from '@/api/itims/versionpublish'
import waves from '@/directive/waves' // 水波纹指令
import { parseTime, formatDate, formatDatetime  } from '@/utils'
import { getToken } from '@/utils/auth'

export default {
  name: 'appInfoFile',
  directives: {
    waves
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        appName: undefined,
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      temp: {
        id: undefined,
        appName: undefined,
        appId: undefined,
        appType: undefined,
        fileName: undefined,
        status: undefined,
        fileStoreId: undefined,
        fileVersion: undefined,
        remark: undefined,
        isDeleted: 0,
        gmtCreate: null,
        gmtModified: null
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogDetailVisible:false,
      pvData: [],
      rules: {
        appName: [{ required: true, message: 'appName is required', trigger: 'change' }],
        fileVersion: [{ required: true, message: 'fileVersion is required', trigger: 'change' }],
        isBoutique: [{ required: true, message: 'isBoutique is required', trigger: 'change' }],
        isCanRemove: [{ required: true, message: 'isCanRemove is required', trigger: 'change' }],
        isDisplay: [{ required: true, message: 'isDisplay is required', trigger: 'change' }]
      },
      fileList: [],
      listN: [],
      totalN: null,
      listLoadingN: true,
      listQueryN: {
        appName: undefined,
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      dialogAppinfoSelectVisible: false,
      fileHeaders:{
          'Authorization': getToken()
      },
      uploadUrl: process.env.BASE_API+'/api/monitor/appInfoFile/fileUpload',
      tempEq: {
        id: undefined,
        versionName: undefined,
        fileId: undefined,
        fileName: undefined,
        remark: undefined,
        isDeleted: 0,
        gmtCreate: null,
        gmtModified: null
      },
      dialogAllocationVisible:false,
      multipleSelection: [],
      listEq: null,
      totalEq: null,
      listLoadingEq: true,
      listQueryEq: {
        equipmentId: undefined,
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      rulesEq: {
        remark: [{ required: true, message: 'remark is required', trigger: 'change' }]
      },
    }
  },
  filters: {
    formatDate(time) {
       var date = new Date(time);
      return formatDate(date, 'yyyy-MM-dd hh:mm');
    },
    formatDatetime(time){
      return formatDatetime(time);
    }

  },
  created() {
    this.getList()
    this.listdetail = []
    this.listLoadingdetail = false
  },
  methods: {
    getList() {
      this.listLoading = true
      const param = {
        'body': {
          "appInfoFileDTO":{
            "appName":this.listQuery.appName
          },
          "pageInfo":{
            "page":this.listQuery.page,
            "pageSize":this.listQuery.limit
          }
        }
      }
      getAppInfoFilePageList(param).then(response => {
        this.list = response.body.appInfoFileDTOList
        this.total = response.body.pageInfo.rowCount
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        appName: undefined,
        appId: undefined,
        appType: undefined,
        fileName: undefined,
        status: undefined,
        fileStoreId: undefined,
        fileVersion: undefined,
        remark: undefined,
        isDeleted: 0,
        gmtCreate: null,
        gmtModified: null
      }
    },
    handleCreate() {
      this.resetTemp()
      this.fileList=[]
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const data = {
            'body': {
              "appInfoFileDTO":{
                appName: this.temp.appName,
                appId: this.temp.appId,
                fileName: this.temp.fileName,
                status: 0,
                fileStoreId: this.temp.fileStoreId,
                fileVersion: this.temp.fileVersion,
                remark: this.temp.remark,
                isDeleted: 0,
              }
            }
          }
          // this.temp.appId = parseInt(Math.random() * 100) + 1024 // mock a id
          saveAppInfoFile(data).then(response => {
            this.list.unshift(response.body.appInfoFileDTO)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.gmtModified = new Date()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          const data = {
            'body': {
              "appInfoFileDTO":{
                id: this.temp.id,
                appName: this.temp.appName,
                appId: this.temp.appId,
                fileName: this.temp.fileName,
                status: this.temp.status,
                fileStoreId: this.temp.fileStoreId,
                fileVersion: this.temp.fileVersion,
                remark: this.temp.remark,
                isDeleted: 0,
              }
            }
          }
          updateAppInfoFile(data).then(response => {
            const appInfoFileDTO = response.body.appInfoFileDTO;
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, tempData)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该应用文件信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          const data = {
              'body': {
                  "appInfoFileDTO":{
                    "id": row.id
                  }
                }
              }
              deleteAppInfoFile(data).then(response => {
                const appInfoFileDTO = response.body.appInfoFileDTO;
                for (const v of this.list) {
                  if (v.id === this.temp.id) {
                    const index = this.list.indexOf(v)
                    this.list.splice(index, 1, appInfoFileDTO)
                    break
                  }
                }
                this.$notify({
                  title: '成功',
                  message: '删除成功',
                  type: 'success',
                  duration: 2000
                })
              })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)

      }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    handleDetail(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogDetailVisible = true
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    getListN() {
      this.listLoadingN = true
      const param = {
        'body': {
          "appInfoDTO":{
            "appName":this.listQueryN.appName
          },
          "pageInfo":{
            "page":this.listQueryN.page,
            "pageSize":this.listQueryN.limit
          }
        }
      }
      getAppInfoPageList(param).then(response => {
        this.listN = response.body.appInfoDTOList
        this.totalN = response.body.pageInfo.rowCount
        this.listLoadingN = false
      })
    },
    handleSizeChangeN(val) {
      this.listQueryN.limit = val
      this.getList()
    },
    handleCurrentChangeN(val) {
      this.listQueryN.page = val
      this.getListN()
    },
    handleFilterN() {
      this.listQuery.page = 1
      this.getListN()
    },
    handleSelect(row){
      this.temp.appId = row.id
      this.temp.appName = row.appName
      this.dialogAppinfoSelectVisible = false
    },
    selectAppinfo(){
      this.dialogAppinfoSelectVisible = true
      this.getListN()
    },
    uploadError(err, file, fileList) {
        console.log('进入uploadError')
        console.log('err',err)
        console.log('file',file)
        console.log('fileList',fileList)
        // 上传失败
        this.$message.error(err);
        this.reset();
      },
    uploadSuccess(response, file, fileList) {
        const appInfoFileDTO =  response.body.appInfoFileDTO
        // 上传成功
        if(response.code==='000000'){
          console.log(appInfoFileDTO.id)
          this.temp.fileStoreId = appInfoFileDTO.id
          this.temp.fileName = appInfoFileDTO.fileName
          console.log(this.temp.fileStoreId)
          this.$message({
            message: '上传成功！',
            type: 'success'
          });
        }else {
          this.$message({
            message: response.msg,
            type: 'error'
          });
        }
      },
      handleDownload(row){
        window.location.href= process.env.BASE_API+'/api/monitor/appInfoFile/fileDownload?id='+row.fileStoreId
      },
      beforeAvatarUpload(file) {
        var testmsg=file.name.substring(file.name.lastIndexOf('.')+1)
        const isJPG = file.type === 'apk';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 apk 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      handlePublish(row){
        this.getListEq()
        this.dialogAllocationVisible = true
        this.tempEq.versionName = row.fileVersion
        this.tempEq.fileId = row.id
        this.tempEq.fileName = row.fileName
      },
    saveVersionPublish(){
      let arr = []
      if(this.multipleSelection.length === 0){
        this.$notify({
            title: '警告',
            message: '请选择终端！！！',
            type: 'warning',
            duration: 2000
          })
        return
      }
      this.multipleSelection.forEach(row =>{
        arr.push(row.equipmentId)
      })
      this.$refs['eqdataForm'].validate((valid) => {
        if (valid) {
          const param = {
            'body': {
              "versionPublishDTO":{
                "versionName": this.tempEq.versionName,
                "fileId": this.tempEq.fileId,
                "fileName": this.tempEq.fileName,
                "isDeleted":0,
                "remark": this.tempEq.remark,
                "equipmentList": arr
              }
            }
          }
          saveVersionPublish(param).then(response => {
            // if('000000' === response.body.code){
                this.$notify({
                  title: '成功',
                  message: '保存成功',
                  type: 'success',
                  duration: 2000
                })
            // }else{
            //      this.$notify({
            //       title: '发布失败',
            //       message: response.body.msg,
            //       type: 'error',
            //       duration: 2000
            //     })
            // }

            this.dialogAllocationVisible = false
          })
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
     handleSizeChangeEq(val) {
      this.listQueryEq.limit = val
      this.getListEq()
    },
    handleCurrentChangeEq(val) {
      this.listQueryEq.page = val
      this.getListEq()
    },
    handleFilterEq() {
      this.listQueryEq.page = 1
      this.getListEq()
    },
    getListEq() {
      this.listLoadingEq = true
      const param = {
        'body': {
          "itimsTerminalDTO":{
            "equipmentId":this.listQueryEq.equipmentId
          },
          "pageInfo":{
            "page":this.listQueryEq.page,
            "pageSize":this.listQueryEq.limit
          }
        }
      }
      getTerminalList(param).then(response => {
        this.listEq = response.body.itimsTerminalDTOList
        this.totalEq = response.body.pageInfo.rowCount
        this.listLoadingEq = false
      })
    },
  }
}
</script>
